/**
 * 可以使用Result处理问题
 * 关注点一:Result的？处理
 *   使用？表示以下表达式
 *   match xxx {
 *      Ok(v) => v,
 *      Err(e) => return Err(e),
 *   }
 * 关注点二:Result的限定写法
 *   一种是 Result<T, E>
 *   另外一种是Result<T>  ,这是常常出现的，这种情况就表示E可以是任意的
 *   还有一种是特别的Result<()>，这种情况表示T是()
 */

use std::fs::File;
use std::io::{self, Read};
use std::io::ErrorKind;

fn main() {
    //不用？处理异常
    read_hello();

    //使用？处理异常
    let  result=  match read_from_file(){     
        Ok(info) => println!("再次...成功读取到内容:\n{}",info),
        Err(e) => eprintln!("Problem reading the file: {:?}", e),  
    };

    //使用?+链式
    let  resultChain=  match read_hello_from_file(){     
        Ok(info) => println!("再三...成功读取到内容:\n{}",info),
        Err(e) => eprintln!("Problem reading the file: {:?}", e),  
    };
}

fn read_hello(){
    let greeting_file_result = File::open("hello.txt");
    let mut greeting_file = match greeting_file_result {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating the file: {e:?}"),
            },
            other_error => {
                panic!("Problem opening the file: {other_error:?}");
            }
        },
    };

    let mut info = String::new();

    let r=greeting_file.read_to_string(&mut info);
    match r {
        Ok(_) => println!("成功读取到内容:\n{}",info),
        Err(e) => eprintln!("Problem reading the file: {:?}", e),
    }; 
}

fn read_from_file() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}

fn read_hello_from_file() -> Result<String, io::Error> {
    let mut username = String::new();
    File::open("hello.txt")?.read_to_string(&mut username)?;
    Ok(username)
}